#include "adc.h"

uint16_t adcValueRegular[3];

void AdcRcuConfig(void)
{
	rcu_periph_clock_enable(RCU_ADC0);
	
	rcu_periph_clock_enable(RCU_DMA0);
	
	rcu_periph_clock_enable(RCU_CKADC_CKAPB2_DIV4);
}

void AdcDmaConfig(void)
{
	dma_parameter_struct dma_data_parameter;

	dma_deinit(DMA0, DMA_CH0);

	dma_data_parameter.periph_addr  = (uint32_t)(&ADC_IDATA0(ADC0));
	dma_data_parameter.periph_inc   = DMA_PERIPH_INCREASE_ENABLE;
	dma_data_parameter.memory_addr  = (uint32_t)(adcValueRegular);
	dma_data_parameter.memory_inc   = DMA_MEMORY_INCREASE_ENABLE;
	dma_data_parameter.periph_width = DMA_PERIPHERAL_WIDTH_16BIT;
	dma_data_parameter.memory_width = DMA_MEMORY_WIDTH_16BIT;
	dma_data_parameter.direction    = DMA_PERIPHERAL_TO_MEMORY;
	dma_data_parameter.number       = 3;
	dma_data_parameter.priority     = DMA_PRIORITY_HIGH;
	dma_init(DMA0, DMA_CH0, &dma_data_parameter);
	
	dma_circulation_enable(DMA0, DMA_CH0);

	dma_channel_enable(DMA0, DMA_CH0);
}

void Adc0Config(void)
{
	adc_mode_config(ADC_MODE_FREE);

	adc_special_function_config(ADC0, ADC_CONTINUOUS_MODE, DISABLE);

	adc_special_function_config(ADC0, ADC_SCAN_MODE, ENABLE);

	adc_data_alignment_config(ADC0, ADC_DATAALIGN_RIGHT);

	adc_channel_length_config(ADC0, ADC_INSERTED_CHANNEL, 3);

	adc_inserted_channel_config(ADC0, 0, ADC_CHANNEL_0, ADC_SAMPLETIME_7POINT5);
	adc_inserted_channel_config(ADC0, 1, ADC_CHANNEL_1, ADC_SAMPLETIME_7POINT5);
	adc_inserted_channel_config(ADC0, 2, ADC_CHANNEL_2, ADC_SAMPLETIME_7POINT5);

	adc_external_trigger_source_config(ADC0, ADC_INSERTED_CHANNEL, ADC0_1_EXTTRIG_INSERTED_T0_CH3);
	adc_external_trigger_config(ADC0, ADC_INSERTED_CHANNEL, ENABLE);

	//adc_dma_mode_enable(ADC0);

	adc_interrupt_flag_clear(ADC0, ADC_INT_EOC);
	adc_interrupt_flag_clear(ADC0, ADC_INT_EOIC);
	
	adc_interrupt_enable(ADC0, ADC_INT_EOIC);
	
	adc_enable(ADC0);

	adc_calibration_enable(ADC0);
}

void AdcConfig(void)
{
	nvic_irq_enable(ADC0_1_IRQn,0U, 0U);
	
	AdcRcuConfig();
	Adc0Config();
}